package cn.alise.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.alise.consts.BaseConsts;
import cn.alise.exception.AuthorizationException;
import cn.alise.qdp.model.user.User;

/**
 * 是否登录
 * @author CHENH
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 *
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 *
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		if (session != null) {
			User account = (User) session.getAttribute(BaseConsts.IUser.USER_SESSION_KEY);
			if (account == null) {
				throw new AuthorizationException("登录session无效！");
			} else {
				// 保存信息到Session中
				session.setAttribute(BaseConsts.IUser.USER_NAME, account.getUserName());//用户名
				session.setAttribute(BaseConsts.IUser.USER_ID, account.getUserId());//用户id
				session.setAttribute(BaseConsts.IUser.ACCOUNT, account.getAccount());//账号
				session.setAttribute(BaseConsts.IUser.ROLE_NAME, account.getRoleNameArr());//角色名称
				return true;
			}
		} else {
			throw new AuthorizationException("登录session无效！");
		}
	}
}